/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListGenMain.java
 *
 * Created on 2011-5-21, 12:41:11
 */
package listgen.ui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;


/**
 *
 * @author Administrator
 */
public class ListGenMain extends javax.swing.JFrame {
    private static int selectedPathMaxLength = 30;

    /** Creates new form ListGenMain */
    public ListGenMain(String _tmp) {
        
        fileName = _tmp;
		
                
        initComponents();
		Toolkit kit = Toolkit.getDefaultToolkit();    // 定义工具包
		Dimension screenSize = kit.getScreenSize();   // 获取屏幕的尺寸
		int	screenWidth = screenSize.width/2;         // 获取屏幕的宽
		int	screenHeight = screenSize.height/2;       // 获取屏幕的高
		int	height = this.getHeight();
		int	width = this.getWidth();
		setLocation(screenWidth-width/2, screenHeight-height/2);        
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
        
    @Action
    public void generateList() throws IOException
    {
        if (selectedPath == null)
        {
            JOptionPane.showMessageDialog(null, "You need to set the Path", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
//        fileName = "testtest";
        listFile = new File(selectedPath.toString() + File.separator + fileName + ".txt");
        if (listFile.exists())
	{
            JOptionPane.showMessageDialog(null, "File has existed", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        } else
        {
            try {
                listFile.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(ListGenMain.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        fileWriter = new FileWriter(listFile);
        fileWriter.write(yearComboBox.getSelectedItem().toString() + ".");
        fileWriter.write(monthComboBox.getSelectedItem().toString() + ".");
	fileWriter.write(dayComboBox.getSelectedItem().toString() + System.getProperty("line.separator"));
        scanFiles(selectedPath);
        fileWriter.close();
        JOptionPane.showMessageDialog(null, "List has generated", "Complete", JOptionPane.INFORMATION_MESSAGE);
    }
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        pathStrLabel = new javax.swing.JLabel();
        pathLabel = new javax.swing.JLabel();
        setPathButton = new javax.swing.JButton();
        dateStrLabel = new javax.swing.JLabel();
        genButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();
        Date today = new Date();
        yearComboBox = new javax.swing.JComboBox();
        monthComboBox = new javax.swing.JComboBox();
        dayComboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Addsongs Tool v2.0 Login: " + fileName);
        setName("Form"); // NOI18N
        setResizable(false);

        mainPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setOpaque(false);
        mainPanel.setPreferredSize(new java.awt.Dimension(490, 150));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(listgen.ListGenApp.class).getContext().getResourceMap(ListGenMain.class);
        pathStrLabel.setText(resourceMap.getString("pathStrLabel.text")); // NOI18N
        pathStrLabel.setName("pathStrLabel"); // NOI18N

        pathLabel.setText(resourceMap.getString("pathLabel.text")); // NOI18N
        pathLabel.setName("pathLabel"); // NOI18N

        setPathButton.setText(resourceMap.getString("setPathButton.text")); // NOI18N
        setPathButton.setName("setPathButton"); // NOI18N
        setPathButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                setPathButtonMouseClicked(evt);
            }
        });

        dateStrLabel.setText(resourceMap.getString("dateStrLabel.text")); // NOI18N
        dateStrLabel.setName("dateStrLabel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(listgen.ListGenApp.class).getContext().getActionMap(ListGenMain.class, this);
        genButton.setAction(actionMap.get("generateList")); // NOI18N
        genButton.setText(resourceMap.getString("genButton.text")); // NOI18N
        genButton.setName("genButton"); // NOI18N

        quitButton.setAction(actionMap.get("quit")); // NOI18N
        quitButton.setText(resourceMap.getString("quitButton.text")); // NOI18N
        quitButton.setName("quitButton"); // NOI18N

        for (Integer i = 1900; i <= 2200; i++)
        yearComboBox.addItem(i);
        yearComboBox.setEditor(null);
        yearComboBox.setKeySelectionManager(null);
        yearComboBox.setName("yearComboBox"); // NOI18N
        yearComboBox.setPreferredSize(new java.awt.Dimension(70, 20));
        yearComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ListGenMain.this.itemStateChanged(evt);
            }
        });

        for (Integer i = 1; i <= 12; i++)
        monthComboBox.addItem(i);
        monthComboBox.setEditor(null);
        monthComboBox.setKeySelectionManager(null);
        monthComboBox.setName("monthComboBox"); // NOI18N
        monthComboBox.setPreferredSize(new java.awt.Dimension(70, 20));
        monthComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ListGenMain.this.itemStateChanged(evt);
            }
        });

        dayComboBox.setEditor(null);
        dayComboBox.setKeySelectionManager(null);
        dayComboBox.setName("dayComboBox"); // NOI18N
        dayComboBox.setPreferredSize(new java.awt.Dimension(70, 20));
        yearComboBox.setSelectedIndex(today.getYear());
        monthComboBox.setSelectedIndex(today.getMonth());
        dayComboBox.setSelectedItem(today.getDate());

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(dateStrLabel)
                            .addComponent(pathStrLabel)))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(pathLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(setPathButton))
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(yearComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(monthComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(dayComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                                .addComponent(genButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(quitButton)))
                        .addGap(183, 183, 183)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {dayComboBox, monthComboBox, yearComboBox});

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {genButton, quitButton});

        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathStrLabel)
                    .addComponent(pathLabel)
                    .addComponent(setPathButton))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateStrLabel)
                    .addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(monthComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dayComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(genButton)
                    .addComponent(quitButton)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 369, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 135, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void itemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_itemStateChanged
		Integer	maxDate = dayOfMonth[monthComboBox.getSelectedIndex()];
		if (monthComboBox.getSelectedIndex() == 1 && new GregorianCalendar().isLeapYear((Integer) yearComboBox.getSelectedItem()))
			maxDate++;
		
		dayComboBox.removeAllItems();
		for (Integer i = 1; i <= maxDate; i++)
			dayComboBox.addItem(i);
    }//GEN-LAST:event_itemStateChanged

    private void setPathButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_setPathButtonMouseClicked
	if (folderChooser == null) folderChooser = new JFileChooser();
        if (selectedPath != null) folderChooser.setCurrentDirectory(selectedPath);
				folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int	selectionValue = folderChooser.showOpenDialog(mainPanel);
				if (selectionValue == JFileChooser.APPROVE_OPTION) 					
				{
					selectedPath = folderChooser.getSelectedFile();
                                        if (selectedPath.toString().length() < selectedPathMaxLength)
                                            pathLabel.setText(selectedPath.toString());
                                        else 
                                            pathLabel.setText("..." + selectedPath.toString().substring(selectedPath.toString().length() - selectedPathMaxLength));
				}	
    }//GEN-LAST:event_setPathButtonMouseClicked

	        
    /**
     * @param args the command line arguments
  
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ListGenMain().setVisible(true);
            }
        });
    }
       */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel dateStrLabel;
    private javax.swing.JComboBox dayComboBox;
    private javax.swing.JButton genButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JComboBox monthComboBox;
    private javax.swing.JLabel pathLabel;
    private javax.swing.JLabel pathStrLabel;
    private javax.swing.JButton quitButton;
    private javax.swing.JButton setPathButton;
    private javax.swing.JComboBox yearComboBox;
    // End of variables declaration//GEN-END:variables

    private File selectedPath = null, listFile = null;
    private String fileName = null;
    private FileWriter fileWriter = null;
    private JFileChooser folderChooser = null;
    private static final Integer[] dayOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    private void scanFiles(File file) throws IOException {
           Integer  count = 0;
        	File[] artistFolder = file.listFiles();
		for (File artist : artistFolder)
		{
			if (artist.isDirectory())
			{
				File[]	songs = artist.listFiles();
				for (File song : songs)
				{
					if (song.toString().toLowerCase().endsWith(".ksc"))
					{
						count++;
						fileWriter.write(count.toString() + ". " + song.getParentFile().getName() + " - " + song.getName().substring(0, song.getName().lastIndexOf('.')) +  System.getProperty("line.separator"));
					}
				}
			}
		}
    }

}
